package p2pcdnsim.cdn;

import p2pcdnsim.network.DatagramPacket;
import p2pcdnsim.network.DatagramSocket;
import p2pcdnsim.network.GenericAddress;
import p2pcdnsim.network.NetworkAddress;
import p2pcdnsim.report.SimReporter;
import desmoj.core.simulator.Model;
import desmoj.core.simulator.SimTime;

public class VoDClient extends Client {
	

	private NetworkAddress 	dnsAddress;
	private int 			requestObjectID;
	private SimTime 		time;

	public VoDClient(Model owner, String name, String clientID, ClientComunity comunity) {
		super(owner, name, clientID, comunity);
	}
	
	@Override
	protected void run() {
		//Start time to calculate the start-up delay
		time = this.currentTime();
		
		DatagramSocket socket = this.createDatagramSocket();
		//System.out.println("["+this.currentTime()+"] VoDClient: sending a packet to "+dnsAddress);
		
		DatagramPacket packet = new DatagramPacket(socket.getAddress(),socket.getPort(),dnsAddress,25);	
		//packet.setMessage(new DNSMessage("cdn.com")); //Modification - Rafael***********
		packet.setMessage(new DNSMessage());
		
		socket.send(packet);	
		packet = socket.receive();
		
		//**********Modification - Rafael***********
		//DatagramPacket packet1 = new DatagramPacket(socket.getAddress(),socket.getPort(),dnsAddress,25);
		//packet1.setMessage(new DNSMessage(packet.getMessage().toString()));
		//socket.send(packet1);
		
	//	packet1 = socket.receive();
		
		
		DNSMessage response = (DNSMessage)packet.getMessage();
		NetworkAddress surrogateAddress = new GenericAddress(response.getMsg());
		
		//System.out.println("["+this.currentTime()+"] VoDClient: datagram received from "+packet.getSourceAddress()+": "+response.getMsg());
		
		//Sending request to Surrogate
		packet = new DatagramPacket(socket.getAddress(),socket.getPort(),surrogateAddress,80);
		packet.setMessage(new ObjectRequest(requestObjectID));
		socket.send(packet);
		
		//Receives content
		long size = 0;
		VideoContent fragment;
		do {
			fragment = (VideoContent)socket.receive().getMessage();
			if (size == 0)
				SimReporter.getInstance().invokeReporter(SimReporter.STARTUP_DELAY, "update",this.currentTime().getTimeValue() - time.getTimeValue());
			size+=fragment.getLength();
		} while(!fragment.isLastFragment());
		//System.out.println(size);
		
		socket.close();
		comunity.disposeClient(this);
	}

	public void setDNSAddress(NetworkAddress dns) {
		this.dnsAddress = dns;
	}

	public void setRequestObject(int objectID) {
		this.requestObjectID = objectID;
	}

}
